package com.conduit.comnands;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.python.core.util.FileUtil;

import com.conduit.commands.prototype.AbstractCommand;
import com.conduit.enums.ResultCode;

public class DeleteFileCommand extends AbstractCommand {

	public DeleteFileCommand() {
		// delete file <file / dir location>
		commandSyntax = "delete file\\s{2,}(.*)";
	}

	@Override
	public void executeWithArgs(String args) {
		if (!args.matches(commandSyntax)) {
			setResult("Error in Command's syntax (\"" + args + "\")");
			setResultCode(ResultCode.Error);
			return;
		}
		Matcher matcher = Pattern.compile(commandSyntax).matcher(args);
		if (matcher.find()) {
			File toDelete = new File(matcher.group(1));
			try {
				fileDelete(toDelete);
			} catch (Exception e) {
				setResult(e.getMessage());
				setResultCode(ResultCode.Error);
			}
			setResult("File Was Successesfuly Deleted");
			setResultCode(ResultCode.Successes);
		}

	}

	private static void fileDelete(File srcFile) throws FileNotFoundException,
			IOException {
		// Checks if file is a directory
		if (srcFile.isDirectory()) {
			// Gathers files in directory
			File[] b = srcFile.listFiles();
			for (int i = 0; i < b.length; i++) {
				// Recursively deletes all files and sub-directories
				fileDelete(b[i]);
			}
			// Deletes original sub-directory file
			srcFile.delete();
		} else {
			// if file is a file
			srcFile.delete();
		}
	}
	
	@Override
	public String getCommandName() {
		// TODO Auto-generated method stub
		return "Delete File"; 
	}

}
